from django.db import transaction
from rest_framework.views import APIView
from rest_framework import generics
from apps.article.models import Article
from apps.member.models import MemberRecord
from utils import response_error, response_ok
from utils.custom_modelviewset import CustomModelViewSet
from utils.exceptions import CustomError
from utils.permission import IsMemberUser
from utils.wechat_applet import WeChatApplet
from .models import Comment
from .serializers import CommentAppSerializer, CommentArticleAppSerializer
from .filters import CommentFilter


class CommentViewSet(CustomModelViewSet):
    permission_classes = [IsMemberUser, ]
    queryset = Comment.objects.filter(delete=False)
    serializer_class = CommentAppSerializer

    def create(self, request, *args, **kwargs):
        try:
            content = request.data.get('content', None)
            article_id = request.data.get('article_id', None)
            if content:
                # 小程序敏感词校验
                wechat_applet = WeChatApplet()
                wechat_applet.wx_check_content(content)

            with transaction.atomic():
                article = Article.get_instance_by_id(article_id)
                Comment.objects.create(member=self.request.user.member, content=content, article=article)
        except Exception as e:
            return response_error(str(e))
        return response_ok()


class CommentArticleViewSet(generics.ListAPIView):
    queryset = Comment.objects.filter(delete=False)
    serializer_class = CommentArticleAppSerializer

    def filter_queryset(self, queryset):
        f = CommentFilter(self.request.GET, queryset=self.queryset)
        return f.qs


class CommentLikeView(APIView):
    '''点赞'''
    permission_classes = [IsMemberUser, ]

    def get(self, request, pk):
        try:
            comment = Comment.get_instance_by_id(pk)
            with transaction.atomic():
                _, messgae = MemberRecord.like_operate(comment, self.request.user.member)
                return response_ok(messgae)
        except CustomError as e:
            return response_error(e.get_error_msg())
        except Exception as e:
            return response_error(str(e))
